package com.injurydetection.www.util.network;

import android.util.Log;

import com.injurydetection.www.constants.Constants;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by sunguiyong on 2020/5/28
 * 自定义拦截器多种baseUrl配置
 */
public class MyInterceptor implements Interceptor {
    //    public static String iv;
//    public static String secretKey;
    private static final String TAG = "MyInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取Request
        Request request = chain.request();
        //获取request的创建者builder
        Request.Builder builder = request.newBuilder();
        //从request中获取headers，通过给定的键urlname
        List<String> headerValues = request.headers("base_url");
        if (headerValues != null && headerValues.size() > 0) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader("base_url");
            //匹配获得新的BaseUrl
            String headerValue = headerValues.get(0);
            HttpUrl newBaseUrl;
            if ("two".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(Constants.BASE_URL2);

            }
//            else if ("two".equals(headerValue)) {
//                newBaseUrl = HttpUrl.parse(Constants.BASE_URL2);
//            }
            else {
                newBaseUrl = HttpUrl.parse(Constants.BASE_URL);
            }
            //从request中获取原有的HttpUrl实例oldHttpUrl
            HttpUrl oldHttpUrl = request.url();
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .removePathSegment(0)
                    .build();
            //重建这个request，通过builder.url(newFullUrl).build()；
            //然后返回一个response至此结束修改
            return chain.proceed(builder.url(newFullUrl).build());
        } else {
            return chain.proceed(request);
        }
    }
}
